<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\JasminumMenu\Controllers;

use Criteria;
use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaFileSystemExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Extensions\HttpExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\GotchaSettingsQuery;
use GotchaDatabase\JasminumMenus;
use GotchaDatabase\JasminumMenusPeer;
use GotchaDatabase\JasminumMenusQuery;
use GotchaDatabase\om\BaseJasminumMenusPeer;

class AdminController extends Controller {
    private $allowedExtensions = array('pdf');

    public function Index() {
        return parent::View();
    }

    public function Create() {
        return parent::View();
    }

    public function CreateFile() {
        return parent::View();
    }

    public function CreatePost() {
        $http = new HttpExtension();

        if(empty($_POST['Title'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=1'));
            exit;
        }

        // Validate file
        if($_FILES['Filename']['error'] != 0) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=2'));
            exit;
        }

        if(isset($_FILES['Filename']['name'])) {
            $file = explode('.', $_FILES['Filename']['name']);
            $fileExtension = end($file);
            if(!in_array($fileExtension, $this->allowedExtensions)) {
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=3'));
                exit;
            }
        } else {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=5'));
            exit;
        }

        if(isset($_FILES['Filename']['size'])) {
            if($_FILES['Filename']['size'] > 1024000) { // More than 10MB
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=7'));
                exit;
            }
        } else {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=6'));
            exit;
        }

        // Check file existence
        $settings = GotchaSettingsQuery::create()
                        ->findOneByStrongName('PdfMenuDir');
        $menuDir = $settings->getValue();

        if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['Filename']['name']), new String(GOTCHA_ROOT_DIR.$menuDir)) == true) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=8'));
            exit;
        }

        // File passed validation, upload it
        move_uploaded_file($_FILES['Filename']['tmp_name'], GOTCHA_ROOT_DIR.DIRECTORY_SEPARATOR.$menuDir.DIRECTORY_SEPARATOR.$_FILES['Filename']['name']);

        // Add new menu
        try {
            $menu = new JasminumMenus();
            $menu->setTitle($_POST['Title']);
            $menu->setFilename($_FILES['Filename']['name']);
            $menu->setIsActive(0);
            $menu->setType('footer');
            $menu->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?create=1'));
        exit;
    }

    public function CreateFilePost() {
        $http = new HttpExtension();

        if(empty($_POST['Title'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=1'));
            exit;
        }

        if(is_null($_POST['Description'])) {
            $_POST['Description'] = '';
        }

        // Validate file
        if($_FILES['Filename']['error'] != 0) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=2'));
            exit;
        }

        if(isset($_FILES['Filename']['name'])) {
            $fileExtension = end(explode('.', $_FILES['Filename']['name']));
            if(!in_array($fileExtension, $this->allowedExtensions)) {
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=3'));
                exit;
            }
        } else {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=5'));
            exit;
        }

        if(isset($_FILES['Filename']['size'])) {
            if($_FILES['Filename']['size'] > 1024000) { // More than 10MB
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=7'));
                exit;
            }
        } else {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=6'));
            exit;
        }

        // Check file existence
        $settings = GotchaSettingsQuery::create()
            ->findOneByStrongName('PdfMenuDir');
        $menuDir = $settings->getValue();

        if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['Filename']['name']), new String(GOTCHA_ROOT_DIR.$menuDir)) == true) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Create?error=8'));
            exit;
        }

        // File passed validation, upload it
        move_uploaded_file($_FILES['Filename']['tmp_name'], GOTCHA_ROOT_DIR.$menuDir.$_FILES['Filename']['name']);

        // Add new menu
        try {
            $menu = new JasminumMenus();
            $menu->setTitle($_POST['Title']);
            $menu->setFilename($_FILES['Filename']['name']);
            $menu->setIsActive(0);
            $menu->setType('file');
            $menu->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?create=2'));
        exit;
    }

    public function Activate() {
        $http = new HttpExtension();

        if(!isset($_GET['id']) || empty($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?error=1'));
            exit;
        }

        $menu = JasminumMenusQuery::create()
                    ->findOneById($_GET['id']);
        if($menu->getIsActive() == 0) {
            JasminumMenusQuery::create()
                ->filterByIsActive(1)
                    ->update(array('IsActive' => 0));

            JasminumMenusQuery::create()
                ->findOneById($_GET['id'])
                    ->setIsActive(1)
                        ->save();
        } else {
            JasminumMenusQuery::create()
                ->findOneById($_GET['id'])
                    ->setIsActive(0)
                        ->save();
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?activate=1'));
        exit;
    }

    public function Edit() {
        return parent::View();
    }

    public function EditFile() {
        return parent::View();
    }

    public function EditPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['Title'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=1&id='.$_POST['Id']));
            exit;
        }

        $menu = JasminumMenusQuery::create()
                        ->findOneById($_POST['Id'])
                            ->getFilename();

        // Check if user chose new menu
        if(isset($_FILES['Filename']['name']) && !empty($_FILES['Filename']['name'])) {
            // Check if it's a  new file
            if($menu != $_FILES['Filename']['name']) {
                // Validate file
                if($_FILES['Filename']['error'] != 0) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=2&id='.$_POST['Id']));
                    exit;
                }

                if(isset($_FILES['Filename']['name'])) {
                    $fileExtension = end(explode('.', $_FILES['Filename']['name']));
                    if(!in_array($fileExtension, $this->allowedExtensions)) {
                        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=3&id='.$_POST['Id']));
                        exit;
                    }
                } else {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=5&id='.$_POST['Id']));
                    exit;
                }

                if(isset($_FILES['Filename']['size'])) {
                    if($_FILES['Filename']['size'] > 1024000) { // More than 10MB
                        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=7&id='.$_POST['Id']));
                        exit;
                    }
                } else {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=6&id='.$_POST['Id']));
                    exit;
                }

                // Check file existence
                $settings = GotchaSettingsQuery::create()
                    ->findOneByStrongName('PdfMenuDir');
                $menusDir = $settings->getValue();

                if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['Filename']['name']), new String(GOTCHA_ROOT_DIR.$menusDir)) == true) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=8&id='.$_POST['Id']));
                    exit;
                }

                // File passed validation, upload it
                move_uploaded_file($_FILES['Filename']['tmp_name'], GOTCHA_ROOT_DIR.'\Media\JasminumMenu\\'.$_FILES['Filename']['name']);
            }
        } else {
            $_FILES['Filename']['name'] = $menu;
        }

        // Update
        try {
            JasminumMenusQuery::create()
                    ->findOneById($_POST['Id'])
                        ->setTitle($_POST['Title'])
                        ->setIsActive(0)
                        ->setType('footer')
                        ->setFilename($_FILES['Filename']['name'])
                            ->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?edit=1'));
        exit;
    }

    public function EditFilePost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['Title'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=1&id='.$_POST['Id']));
            exit;
        }

        $menu = JasminumMenusQuery::create()
            ->findOneById($_POST['Id'])
            ->getFilename();

        // Check if user chose new menu
        if(isset($_FILES['Filename']['name']) && !empty($_FILES['Filename']['name'])) {
            // Check if it's a  new file
            if($menu != $_FILES['Filename']['name']) {
                // Validate file
                if($_FILES['Filename']['error'] != 0) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=2&id='.$_POST['Id']));
                    exit;
                }

                if(isset($_FILES['Filename']['name'])) {
                    $fileExtension = end(explode('.', $_FILES['Filename']['name']));
                    if(!in_array($fileExtension, $this->allowedExtensions)) {
                        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=3&id='.$_POST['Id']));
                        exit;
                    }
                } else {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=5&id='.$_POST['Id']));
                    exit;
                }

                if(isset($_FILES['Filename']['size'])) {
                    if($_FILES['Filename']['size'] > 1024000) { // More than 10MB
                        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=7&id='.$_POST['Id']));
                        exit;
                    }
                } else {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=6&id='.$_POST['Id']));
                    exit;
                }

                // Check file existence
                $settings = GotchaSettingsQuery::create()
                    ->findOneByStrongName('PdfMenuDir');
                $menusDir = $settings->getValue();

                if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['Filename']['name']), new String(GOTCHA_ROOT_DIR.$menusDir)) == true) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus/Edit?error=8&id='.$_POST['Id']));
                    exit;
                }

                // File passed validation, upload it
                move_uploaded_file($_FILES['Filename']['tmp_name'], GOTCHA_ROOT_DIR.'\Media\JasminumMenu\\'.$_FILES['Filename']['name']);
            }
        } else {
            $_FILES['Filename']['name'] = $menu;
        }

        // Update
        try {
            JasminumMenusQuery::create()
                ->findOneById($_POST['Id'])
                ->setTitle($_POST['Title'])
                ->setIsActive(0)
                ->setType('file')
                ->setFilename($_FILES['Filename']['name'])
                ->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?edit=2'));
        exit;
    }

    public function Delete() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?error=2'));
            exit;
        }

        // Delete element
        try {
            JasminumMenusQuery::create()->findOneById($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?delete=1'));
        exit;
    }

    public function DeleteFile() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?error=2'));
            exit;
        }

        // Delete element
        try {
            JasminumMenusQuery::create()->findOneById($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Menus?delete=2'));
        exit;
    }

    public function returnMenus() {
        $menus = JasminumMenusQuery::create()
                    ->filterByType('footer')
                        ->orderById()
                            ->find();

        $html = '';
        foreach($menus as $menu) {
            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>%s</td><td>%s</td><td>[ <a class="activate" href="%s?id=%s">%s</a> | <a href="%s?id=%s">Edytuj</a> | <a href="%s?id=%s" class="delete">Usuń</a> ]</td>', $menu->getTitle(), $menu->getFilename(), ($menu->getIsActive() == 1) ? 'Aktywne' : 'Nieaktywne', parent::UrlContent('/Admin/Jasminum/Menus/Activate'), $menu->getId(), ($menu->getIsActive() == 1) ? 'Dezaktywuj' : 'Aktywuj', parent::UrlContent('/Admin/Jasminum/Menus/Edit'), $menu->getId(), parent::UrlContent('/Admin/Jasminum/Menus/Delete'), $menu->getId());
            $html .= '</tr>';
        }

        if($menus->count() == 0) {
            $html .= '<tr><td colspan="4">Nie ma dodanych menu.</td></tr>';
        }

        return $html;
    }

    public function returnMenuFiles() {
        $menus = JasminumMenusQuery::create()
            ->filterByType('file')
            ->orderById()
            ->find();

        $html = '';
        foreach($menus as $menu) {
            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>%s</td><td>%s</td></td><td>[ <a href="%s?id=%s">Edytuj</a> | <a href="%s?id=%s" class="delete">Usuń</a> ]</td>', $menu->getTitle(), $menu->getFilename(), parent::UrlContent('/Media/JasminumMenu/'.$menu->getFilename()), parent::UrlContent('/Admin/Jasminum/Menus/EditFile'), $menu->getId(), parent::UrlContent('/Admin/Jasminum/Menus/DeleteFile'), $menu->getId());
            $html .= '</tr>';
        }

        if($menus->count() == 0) {
            $html .= '<tr><td colspan="4">Nie ma dodanych menu.</td></tr>';
        }

        return $html;
    }

    public function returnMenu($id) {
        $menu = JasminumMenusQuery::create()
                    ->findOneById($id);
        return $menu;
    }

    public function returnMenuFile($id) {
        $menu = JasminumMenusQuery::create()
                ->filterByType('file')
                ->findOneById($id);
        return $menu;
    }
}